﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YasharEl.Infrastructure.ApplicationModel.Bootstrap.Behavior;
using YasharEl.Infrastructure.ApplicationModel.Bootstrap.Extensibility;
using System.Diagnostics.Contracts;
using System.Configuration;

namespace YasharEl.Infrastructure.ApplicationModel.Bootstrap.Configuration
{
    public class ConfigurationSectionBehavior : IBehavior<IBootstrappingExtension>
    {
        private readonly IConfigurationSectionBehaviorFactory factory;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationSectionBehavior"/> class.
        /// </summary>
        public ConfigurationSectionBehavior()
            : this(new DefaultConfigurationSectionBehaviorFactory())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationSectionBehavior"/> class.
        /// </summary>
        /// <param name="factory">The factory.</param>
        public ConfigurationSectionBehavior(IConfigurationSectionBehaviorFactory factory)
        {
            this.factory = factory;
        }

        public void Behave(IEnumerable<IBootstrappingExtension> extensions)
        {
            foreach (IBootstrappingExtension extension in extensions)
            {
                IConsumeConfigurationSection consumer = this.factory.CreateConsumeConfigurationSection(extension);
                IHaveConfigurationSectionName sectionNameProvider = this.factory.CreateHaveConfigurationSectionName(extension);
                ILoadConfigurationSection sectionProvider = this.factory.CreateLoadConfigurationSection(extension);

                string sectionName = sectionNameProvider.SectionName;
                ConfigurationSection section = sectionProvider.GetSection(sectionName);

                consumer.Apply(section);
            }
        }

        public string Name
        {
            get { return this.GetType().FullNameToString(); }
        }

        public string Describe()
        {
            return "Automatically provides configuration sections for all bootstrapping extensions.";
        }
    }
}
